package com.nmcc.app_adherence;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.view.View;
import android.content.ComponentName;
import android.content.DialogInterface;
//import android.widget.Button;
import android.content.Context;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import android.os.Process;

public class MainActivity extends Activity {
   // Button btnShowLocation;
	//The Android's default system path of your application database.
	//try save in in sdcard

	private static String CSV_NAME = "GPSData.csv";
	private static String CSV_NAME_PERSONS = "Persons.csv";
	
    //HouseActivity houseA;
   // DataBaseHelper myDbHelper;
    private Button button;
    private Spinner spnHHResultspn;

    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Button b1 = (Button) findViewById(R.id.btnhouse_listing);
        b1.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {
        	   
        	   
        	   
           Intent i = new Intent(MainActivity.this, HousesListActivity.class);
           startActivity(i);
      
           }
        });
        
        
      
        Button b666 = (Button) findViewById(R.id.btnExport);
        b666.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {

        	   
        	   
        	   //Intent i = new Intent(MainActivity.this, ResendBluetoothFile.class);
               //startActivity(i);
        	   
        	   //copyfilesusingfilechannel(arg0);
        	   
               //MarkRecordsAsExported(final View view)
        	  Toast.makeText(getApplicationContext(), "Note: Only Exports houses with DHAp treatment.", Toast.LENGTH_LONG).show();
        	    
        	   
        	   ExportRecordsPreLinker(arg0);
      
               
           }
        });  
        
        
        //btnExportDataToCSVAndODKPracticeTest
        Button b3 = (Button) findViewById(R.id.btnQuit);
        b3.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {
        	   
        	   
        	  // rebootphone(arg0);
        
           android.os.Process.killProcess(android.os.Process.myPid());
           System.exit(1);
        
           }
        });       
  
        //btnExportDataToCSVAndODKPracticeTest
        Button b56 = (Button) findViewById(R.id.btnOdksurveyAdherence);
        b56.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {
        	   Go_To_MainMenu_Linker(arg0);
        	   
           }
        });       
        
        //addItemsOnSpinnerHHResult();
        
    }
    
    public void rebootphone(View view)
    {
    	try{
    		//Runtime.getRuntime().exec("su");
    		
    		Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot now"});
    		
    	} catch(IOException e){
    		
    	}
	
    }
    
    public void copyfilesusingfilechannel(View view){
    	File sdcard = Environment.getExternalStorageDirectory();
    	
     	File fSource=new File("/data/data/com.nmcc.app_adherence/databases/mis_data");
    	File fDestin=new File(sdcard + "/mis_data.db");
    	//check if file exists
        	 boolean alreadyExists = new File("/data/data/com.nmcc.app_adherence/databases/mis_data").exists();
          
        	 //Toast.makeText(getApplicationContext(), "rrrr", Toast.LENGTH_LONG).show();
     	    
        	 try{
        		 
        		 if (alreadyExists) {
        			 copyFileUsingFileChannels(fSource,fDestin);
            	 }
            	 else{
            	  		//do nothing
            	 }
        	 }
        	 	catch(IOException e)
        	 	{
        	 	     e.printStackTrace();
        	 	}
        	 
        	 
    }
    
    private static void copyFileUsingFileChannels(File source, File dest)
            throws IOException {
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            inputChannel = new FileInputStream(source).getChannel();
            outputChannel = new FileOutputStream(dest).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
        } finally {
            inputChannel.close();
            outputChannel.close();
        }
    }
    
     // Go to another screen
    public void Go_To_House_Linker(View view)
     {
 	   //'navigate to another screen'
 	   final Context context = this;
        //give values
 	   Intent intent = new Intent(context, HouseActivity.class);
 	   //intent.putExtra("cluster","22");
 	    startActivity(intent);
     }
    
    // Go to another screen
   public void Go_To_ODKSurvey(View view)
    {


    }
    
   
   public void launchOdkSurvey(View view) {
		//try {
			//System.out.println("Opening ODK Survey");
			//Runtime runTime = Runtime.getRuntime();
			//Process process = runTime.exec("org.opendatakit.survey.android");
			//try {
				//Thread.sleep(5000);
			//} catch (InterruptedException e) {
				//e.printStackTrace();
			//}
			//System.out.println("Closing ODK Survey");
			//process.destroy();
		//} catch (IOException e) {
			//e.printStackTrace();
		//}
	}
   
   
   public void MarkRecordsAsExported(final View view){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure files have been sent successfully, and can now be marked as exported?")
		       .setCancelable(false)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                //MyActivity.this.finish(); //Close  this Activity for example: MyActivity.java
		        	   
		        	   LinkerMarkAllRecordsAsExported(view);	   
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                // some code if you want
		                dialog.cancel();
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();

		
	}
   
   public void ExportRecordsPreLinker(final View view){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("You are about to Export your listing data for adherence monitoring, are you sure you want to proceed?")
		       .setCancelable(false)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                //MyActivity.this.finish(); //Close  this Activity for example: MyActivity.java
		        	   
		        	   ExportDataToCSVLinker();
		        	   SendFileViaBluetoothFromSDCardFolder(view);
		             
		               WereFilesSentSuccessfully(view);	   
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                // some code if you want
		                dialog.cancel();
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();

		
	}
   
   public void ExportGPSDataToCSV(View view){
  	 /////////////////////////////  MySQLiteHelper db = new MySQLiteHelper(this);
  	   //to avoid overwriting in odk survey just send to sd card folder
         // add Books
         //db.DropAllTables();
     ////////////////////////////  db.ExportGPSDataToCSV(CSV_NAME);
        //db.getGPSRecordsCount();
      /////////////////////////// db.ExportPersonsToCSV(CSV_NAME_PERSONS);
      // Toast.makeText(getApplicationContext(), "Files successfully exported to csv. Please check this data in the ODK Survey", 5000).show();
         //new
  	   //now send via bluetooth
  	   //Toast.makeText(getApplicationContext(), "Now Sending GPSData and Persons csv files via bluetooth.", 5000).show();
         
  	   //SendFileViaBluetoothFromSDCardFolder(view, "GPSData.csv");
  	   //SendFileViaBluetoothFromSDCardFolder(view, "Persons.csv");
  }
  
   
   public void SendFileViaBluetoothFromSDCardFolder(View view){
	  
	
	   
	   File sdcard = Environment.getExternalStorageDirectory();
		   File f1=new File(sdcard+"/GPSData.csv");
		   File f2=new File(sdcard+"/Persons.csv");

		   Uri csvUri1 = Uri.fromFile(f1);
		   Uri csvUri2 = Uri.fromFile(f2);
		   
		   ArrayList<Uri> csvUris = new ArrayList<Uri>();
		   csvUris.add(csvUri1); // Add your image URIs here
		   csvUris.add(csvUri2);	
	   
		   
	 //...
	   // inside method
	   // Check if bluetooth is supported
	   BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
	   if (btAdapter == null) {
	   // Device does not support Bluetooth
	   // Inform user that we're done.     
	   }
	   // bring up Android chooser
	   Intent intent = new Intent();
	   intent.setAction(Intent.ACTION_SEND_MULTIPLE);
	   
	   //intent.setType("application/csv");
	   //send file 1
	   //intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f) );
	   intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, csvUris);
	   
	   //remove below to have flexibilty on the bluetooth complete action
	   //intent.setPackage("com.mediatek.bluetooth");//"com.android.bluetooth"
	   //can remove above line, or make it as a setting editable
	   
	   //...
	   //startActivity(intent);
	   //send file 2

	   intent.setType("application/csv");
	   startActivity(Intent.createChooser(intent, "Send GPSData and Persons Files Via:"));
	  //startActivity(intent);
	

	    
	} 

   
   public void Go_To_MainMenu_Linker(View view)
   {
      //'navigate to another screen'
      final Context context = this;
      //give values
      Intent intent = new Intent(context, AdherenceActivity.class);
      //intent.putExtra("cluster","22");
       startActivity(intent);
   }	
   
   public void LinkerMarkAllRecordsAsExported(View view){
	   MySQLiteHelper db = new MySQLiteHelper(this);
		
		db.MarkAllExportedGPSRecordsAsExported();
		db.MarkPersonsAsExported();
   }

   public void WereFilesSentSuccessfully(final View view){
 		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 		builder.setMessage("Have files been sent successfuly?")
 		       .setCancelable(false)
 		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
 		           public void onClick(DialogInterface dialog, int id) {
 		                //MyActivity.this.finish(); //Close  this Activity for example: MyActivity.java
 		        	   
 		        	  MarkRecordsAsExported(view);	   
 		           }
 		       })
 		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
 		           public void onClick(DialogInterface dialog, int id) {
 		                // some code if you want
 		                dialog.cancel();
 		           }
 		       });
 		AlertDialog alert = builder.create();
 		alert.show();

 		
 	}
  
   public void ExportDataToCSVLinker(){
		
		  ExportGPSDataToCSV();
	    //Toast.makeText(getApplicationContext(), "Sending GPSData, Persons csv files via bluetooth.", Toast.LENGTH_LONG).show();
	  // SendFileViaBluetoothFromSDCardFolder();
	}
   
   public void ExportGPSDataToCSV(){
  	   MySQLiteHelper db = new MySQLiteHelper(this);
  	   //to avoid overwriting in odk survey just send to sd card folder
         // add Books
    Toast.makeText(getApplicationContext(), "Note: Only those persons who received DHAP treatment will be exported for followups.", Toast.LENGTH_LONG).show();
           
  	   
  	   //db.DropAllTables();
       db.ExportGPSDataToCSV(CSV_NAME);
        //db.getGPSRecordsCount();
    
       db.ExportPersonsToCSV(CSV_NAME_PERSONS);
         //new
  	   //now send via bluetooth
  	   //Toast.makeText(getApplicationContext(), "Now Sending GPSData and Persons csv files via bluetooth.", 5000).show();
         
  	   //SendFileViaBluetoothFromSDCardFolder(view, "GPSData.csv");
  	   //SendFileViaBluetoothFromSDCardFolder(view, "Persons.csv");
  }
   
      
}